
const { BLOCKLIST_PREF, Services, allPrefs, prefs, refreshBlocklist, xpath } = Components.utils.import("resource://exttest/exttest.jsm", {});

function $(selector, node) (node || document).querySelector(selector);
function $$(selector, node) (node || document).querySelectorAll(selector);

function clearPref(name) {
    (name ? [name] : prefs.safe.getNames())
         .forEach(function (name) { prefs.safe.reset(name); });
}
function editPref(name, label) {
    window.openDialog("chrome://exttest/content/edit-list.xul",
                      "exttest-edit",
                      "alwaysRaised,centerscreen,chrome,dialog,modal",
                      name, label);
}

function getTemplate(node, template) {
    let content = template.cloneNode(true);

    for (let attr in xpath("//@*[contains(., '{')]", content))
        attr.value = attr.value.replace(/\{(.*?)\}/g, function (m, m1) node.getAttribute(m1));

    let range = document.createRange();
    range.selectNodeContents(content);
    return range.extractContents();
}

document.addEventListener("DOMContentLoaded", function onDOMContentLoaded() {
    let preferences = $("#preferences");
    let prefsTemplate = $("#template-preference");
    let rowTemplate = $("#template-pref");

    for each (let template in ["headers", "columns"])
        Array.forEach($$("." + template), function (node) {
            node.appendChild(getTemplate(node, $("#template-" + template)));
        });

    for (let node in xpath("//*[@pref]", document)) {
        let pref = node.getAttribute("pref");
        if (!prefs.console.defaults.has(pref))
            prefs.console.defaults.set(pref, true);
        if (!prefs.status.defaults.has(pref))
            prefs.status.defaults.set(pref, true);

        node.appendChild(getTemplate(node, rowTemplate));
        preferences.appendChild(getTemplate(node, prefsTemplate));
    }

}, false);

window.addEventListener("load", function onLoad() {
    window.removeEventListener("load", onLoad, false);

    $("#description").style.maxWidth = $("#tabs").boxObject.width + "px";
    window.sizeToContent();
}, false);

addEventListener("DOMContentLoaded", function onDOMContentLoaded(event) {
    let uri = Services.io.newURI(allPrefs.get(BLOCKLIST_PREF), null, null);

    Array.forEach(document.querySelectorAll(".blocklist-source"), function (elem) {
        uri.host = elem.getAttribute("site");
        elem.value = uri.spec;
    });

    document.getElementById("pref-blocklist").updateElements();
}, false);

